package com.liu.common.utils;

import cn.hutool.core.codec.Base64;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.w3c.dom.Document;
import org.xhtmlrenderer.layout.SharedContext;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;

@Slf4j
public class HtmlToImageUtils {

    /**
     * html转图片
     * @param templateName 模板名称
     * @param templateParam 参数
     * @param generateFilePath 生成的图片路径
     * @throws IOException 抛出异常
     * @throws TemplateException 抛出异常
     */
    public static File htmlToImage(String templateName, Map<String, Object> templateParam, String generateFilePath, Integer width) throws IOException, TemplateException, ParserConfigurationException, SAXException {
        File file1 = new File("src/main/resources/backgroundImage/backgroundImage4.png");
        String encode1 = Base64.encode(file1);
        templateParam.put("imageBase64", encode1);
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateLoader(new ClassTemplateLoader(HtmlToImageUtils.class,"/templates/"));
        Template template = configuration.getTemplate(templateName);
        String processTemplateIntoString = FreeMarkerTemplateUtils.processTemplateIntoString(template, templateParam);
        InputSource inputSource = new InputSource(new StringReader(processTemplateIntoString));
        // 使用html字符串直接写入的方式减少生成时间
//        File templateHtmlFile = new File("src/main/resources/template/template.html");
//        FileWriter fileWriter = FileWriter.create(templateHtmlFile);
//        fileWriter.write(processTemplateIntoString);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(inputSource);
        // 高设置-1可以自适应html的高度
        Java2DRenderer renderer = new Java2DRenderer(document, width, -1);
        SharedContext sharedContext = renderer.getSharedContext();
        sharedContext.setDotsPerPixel(3);
        sharedContext.setDPI(523);
        BufferedImage image = renderer.getImage();
        File file = new File(generateFilePath);
        ImageIO.write(image, "png", file);
        return file;
    }
}
